# coding = utf-8

'''
使用对比增强的相关算法
方法介绍：https://www.cnblogs.com/Leo_wl/p/3324760.html
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math


def find_data(case_id, origion_id, index):
    big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
    big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
    big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
    big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
    big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
    big_image[big_image <= -200] = -200
    big_image[big_image > 250] = 250
    big_image = (big_image + 200) / 450
    big_image = big_image[index]
    big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
    big_liver = big_liver[index]
    big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
    big_tumor = big_tumor[index]
    big_fusion = Image.open(big_fusion)
    return (big_image, big_fusion, big_liver, big_tumor)


def ace(image, n, D):
    image = image*255
    image = image.astype(np.uint8)
    result = np.zeros(image.shape)

    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            x0 = max(0, i-2*n)
            x1 = min(image.shape[0], i+2*n)
            y0 = max(0, j-2*n)
            y1 = min(image.shape[1], j+2*n)
            temp = image[x0:x1, y0:y1]
            mean = np.mean(temp)
            var = np.std(temp) + 0.000001
            value = mean + (D/var)*(image[i][j]-mean)
            result[i][j] = value

    return result


def main():
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=67, origion_id="0415", index=135)

    big_image1 = ace(image=big_image, n=50, D=3)
    big_image2 = ace(image=big_image, n=50, D=10)
    plt.subplot(1, 3, 1)
    plt.imshow(big_image, cmap="gray")
    plt.subplot(1, 3, 2)
    plt.imshow(big_image1, cmap="gray")
    plt.subplot(1, 3, 3)
    plt.imshow(big_image2, cmap="gray")
    plt.show()

    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    liver = big_image
    liver = liver * 255
    liver = liver.astype(np.uint8)
    # liver = cv2.equalizeHist(liver)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    plt.imshow(liver)
    plt.show()



if __name__ == '__main__':
    main()

